package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Lorine
 * @date 2025/3/5 14:30
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("校验失败,请重新登录");
        }
        // 校验token是否合法
        try {
            Claims claims = tokenService.parseToken(token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            if (ObjectUtil.isNull(userId)) {
                response.setStatus(HttpStatus.UNAUTHORIZED);
                throw new BaseException("校验失败,请重新登录");
            }
            UserThreadLocal.set(userId);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new BaseException("校验失败,请重新登录");
        }
    }
}
